package com.itic.web.mem.login.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.demo.modelfiles.persistence.model.ModelFiles;
import com.itic.demo.modelfiles.service.ModelFilesService;
import com.itic.demo.util.PhoneMessgeUtil;
import com.itic.ht.mem.member.persistence.model.WebMember;
import com.itic.ht.mem.member.persistence.model.WebMemberExample;
import com.itic.ht.mem.member.service.WebMemberService;
import com.itic.ht.mem.memberdetail.persistence.model.WebMemberDetail;
import com.itic.ht.mem.memberdetail.service.WebMemberDetailService;
import com.itic.web.mem.login.util.FormDataCodeUtil;
import com.itic.web.mem.login.util.RandomUtil;
import com.itic.web.mem.member.view.MemberView;
import com.itic.web.qo.RegisterData;
import com.itic.web.qo.TokenData;
import com.itic.web.ro.ResResult;
import com.itic.web.util.SmsUtil;
import com.itic.web.util.TokenUtil;

@Service
@Transactional
public class AppMemberService {
	
	@Autowired
	private WebMemberService webMemberService;
    @Autowired
    private WebMemberDetailService webMemberDetailService;
    @Autowired
    private ModelFilesService modelFilesService;

	
	public ResResult getVerificationCode(WebMember temp){
		
		String randomValue = "";
		WebMember baseMember = new WebMember();
		Date VerificationExpireTime = CalendarHelper.getMinuteAfter(new Date(),5);
		try {
			//保存用户信息 ----------注意手机号不可重复需要同步操作
			synchronized (WebMember.class) {
				WebMemberExample example = new WebMemberExample();
				example.createCriteria().andAccountEqualTo(temp.getAccount());
				List<WebMember> list = webMemberService.list(example);
				if(list == null || list.size() == 0){
					baseMember.setAccount(temp.getAccount());
					int randomIndex1 = RandomUtil.randomIndex(1000, 9999);
					randomValue = String.valueOf(randomIndex1);
					baseMember.setVerificationCode(String.valueOf(randomIndex1));
					baseMember.setVerificationExpireTime(VerificationExpireTime);
					
					baseMember.setBalance(new BigDecimal(0));
					baseMember.setExchangePoints(0);
					baseMember.setSumPoints(0);
					//设为普通会员
					baseMember.setCategory("eba618aea92c49dba49cc82d70be52b0");
					webMemberService.add(baseMember);
//					PhoneMessgeUtil.send(temp.getAccount(), randomValue, temp.getAccount());
					SmsUtil.sendValidMessage(temp.getAccount(), randomValue);
				}else{
					//如果用户已申请过注册但没有成功的情况或是password过期
					//如果用户已申请过注册       生成新验证码
					baseMember = list.get(0);
					//用如用户已存在就直接去取验证码          发送验证码
					randomValue  = baseMember.getVerificationCode();
//					PhoneMessgeUtil.send(temp.getAccount(), randomValue, temp.getAccount());
					//判断验证码是否过期
					if(VerificationExpireTime.compareTo(new Date())>0){
						//验证码已过期
						int randomIndex2 = RandomUtil.randomIndex(1000, 9999);
						randomValue = String.valueOf(randomIndex2);
						baseMember.setVerificationCode(String.valueOf(randomIndex2));
						baseMember.setVerificationExpireTime(VerificationExpireTime);
						webMemberService.edit(baseMember);
					}
					SmsUtil.sendValidMessage(temp.getAccount(), randomValue);
				}
			}
			
	
			return ResResult.build(200, "发送成功", randomValue);
		} catch (Exception e) {
			//返回错误代码
			return ResResult.error(200, "发送失败");
		}

	}
	
	//account verification 取得 token 
	public ResResult getToken(WebMember temp){
		
		String userToken = "";
		
       try {
		     //验证改选项
		     if(StringHelper.isEmpty(temp.getAccount()) || StringHelper.isEmpty(temp.getPassword())){
		     	return ResResult.error(1, "用户名或密码为空");
		     }
		     //用户名和验证码对数据库进行验证
		     WebMemberExample example = new WebMemberExample();
		     example.createCriteria().andAccountEqualTo(temp.getAccount()).andPasswordEqualTo(temp.getPassword());
		     List<WebMember> list = webMemberService.list(example);
		     if(list==null || list.size()<= 0){
		     	return ResResult.error(2, "用户名或密码不正确");
		     }
		     
		     //判断每日口令是不是正确
	         userToken = TokenUtil.getUserToken(temp.getAccount());

			 return ResResult.build(200, "取token成功", userToken);
		} catch (Exception e) {
			//返回错误代码
			return ResResult.error(1, "取token失败");
		}

	}
	

	
	/*
	 * 用户注册  用户名 + 验证码  =  换取密码        可以绑了定关联关系
	 * account verification 取得   password  
	 */
	public ResResult getPassWord(RegisterData data){
		
		
		   Date now = new Date();
		   WebMember baseMember = null;
		
	       try {
	             	//验证必选项 帐号 和 密码
	             	if(StringHelper.isEmpty(data.getAccount()) || StringHelper.isEmpty(data.getVerificationCode())){
	             		return ResResult.error(1, "用户名或验证码为空");
	             	}
	             	System.out.println("用户名+验证码="+data.getAccount()+"-"+data.getVerificationCode());
	             	//用户名和验证码对数据库进行验证  ========返回MemberDetail实例
	             	WebMemberExample example = new WebMemberExample();
	             	example.createCriteria().andAccountEqualTo(data.getAccount()).andVerificationCodeEqualTo(data.getVerificationCode());
	             	List<WebMember> list = webMemberService.list(example);
	             	System.out.println("list.size===========****************************============="+list.size());
	             	if(list==null || list.size()<= 0){
	             		return ResResult.error(2, "用户名或验证码无效");
	             	}else{
	             		//取出用户信息   验证一下用户的密码是不是过期
	             		baseMember = list.get(0);
	             		if(baseMember.getExpireTime()!=null){
	             			
	             			Date expireTime = baseMember.getVerificationExpireTime();
	             			if(expireTime.before(now)){
	             				return ResResult.error(3, "验证码已过5分钟");
	             			}
	             			
	             		}
	             		
	             	}
	             	
	             	//把password和token返回给前端         根据用户名和验证码和过期时间生成password
	             	String userpassWord = TokenUtil.getPassWord(baseMember.getAccount(),baseMember.getVerificationCode(),baseMember.getVerificationExpireTime().toString());
	             	baseMember.setPassword(userpassWord);
	             	Date expireTime = CalendarHelper.getDateAfter(new Date(),180);
	             	baseMember.setExpireTime(expireTime);
	             	webMemberService.edit(baseMember);
	             	data.setPassword(userpassWord);
	             	String userToken = TokenUtil.getUserToken(data.getAccount());
	             	data.setToken(userToken);
	             	
	            //先生成自己的二维码
	           if(true){
	        	   System.out.println("********************************1*******************************************");
	             	WebMemberDetail detail = webMemberDetailService.getMemberDetailByAccount(data.getAccount());
	             	System.out.println("********************************2*******************************************");
	             	//如果是第一次时生成推荐码    生成自己的二维码    保存自己的二维码地址
	             	if(detail == null || "".equals(detail)){
	             		System.out.println("********************************3*******************************************");
	             		detail = new WebMemberDetail();
	             		detail.setAccount(data.getAccount());
	             		detail.setInvitationCode(data.getAccount());
	             		//调用远程生成二维码并返回二维码地址
	             		System.out.println("********************************4*******************************************");
	             		//String url ="http://192.168.199.233:8080/hkServer/app/mem/setRelation?subjectId=" + data.getAccount();
	             		String subjectId = data.getAccount();
	             		String codeUrl = null;
	             		try {
	             			System.out.println("********************************5*******************************************");
	             			codeUrl = FormDataCodeUtil.inputStreamUpload( data.getAccount(), subjectId);
						} catch (Exception e) {
							System.out.println("生成用户二维码出错");
						}
	             		System.out.println("********************************6*******************************************");
	             		detail.setPid(data.getInvitationCode());
	             		if(codeUrl!=null && !"".equals(codeUrl)){
	             			System.out.println("********************************7*******************************************");
	             			detail.setFileId(codeUrl);
	             		}
	             		webMemberDetailService.add(detail);
	             	}
	             }
	             	
	             //如果有推荐码 =========执行以下操作
	            if(data.getInvitationCode()!=null && !"".equals(data.getInvitationCode())){
	            	data = createRelation(data);
	            }
	             	
	               return ResResult.build(200, "取token成功", data);
	            
		} catch (Exception e) {
			//返回错误代码
			e.printStackTrace();
			return ResResult.error(4, "注册失败");
		}
		
	}
	
	
	/**
	 *  验证token
	 *  (上级存在   而且自己的pid为空时)         关联用户关系
	 */
	public ResResult assertToken(TokenData temp){
		boolean flag = false;
		try {
		    if(StringHelper.isEmpty(temp.getToken())){
		    	return ResResult.error(1, "token 不存在");
		    }
		    
		    TokenData data = new TokenData();
		    data.setAccount(temp.getAccount());
		    data.setToken(temp.getToken());
		    //判断口令是不是正确
		    flag = TokenUtil.assertUserToken(data);
		    
		    //验证用户验证码是不是过期
         	//验证一下用户的验证码是不是过期
		    Date now = new Date();
		    WebMember member = webMemberService.getMemberByAccount(temp.getAccount());
         	Date expireTime = member.getExpireTime();
         	if(expireTime.before(now)){
         		return ResResult.error(3, "token已过期");
         	}

		    if(flag){
		    	return ResResult.build(200, "验证token成功", flag);
		    }else{
		    	return ResResult.build(2, "验证token失败", flag);
		    }
		} catch (Exception e) {
			//返回错误代码
			return ResResult.error(4, "取token失败");
		}
		
	}
	
	
	/**
	 * 验证自己是不是已绑定上级       验证自己的上级PID是不是已存在
	 */
	public RegisterData createRelation(RegisterData data){
		
		System.out.println("我上级的推荐码是:"+data.getInvitationCode());
		WebMemberDetail baseDetail = null;
		WebMember member = null;
		try {
			baseDetail  = webMemberDetailService.getMemberDetailByAccount(data.getAccount());
			if(baseDetail!=null){
         	   if(!StringHelper.isEmpty(baseDetail.getPid())){
         		  //数据库存中PID为空时操作
         		  if(StringHelper.isEmpty(baseDetail.getPid())){
         		     //首先上级要存在
         		     member = webMemberService.getMemberByAccount(data.getInvitationCode());
         		     if(member!=null){
         		     	//执行关联存储
         		     	baseDetail.setPid(data.getInvitationCode());
         		     	webMemberDetailService.edit(baseDetail);
         		     }else{
         		    	data.setRelationStatus(false);
         		    	data.setRelationMessage("这个用户不存在");
         		     }
         		     
         		}else{
         			//通知前台您的用户关系已绑定
         			data.setRelationStatus(false);
         			data.setRelationMessage("您已绑定其它用户");
         		}
         
         	}else{
         		//新建用户详情关联关系
         		baseDetail.setAccount(data.getAccount());
 		     	baseDetail.setPid(data.getInvitationCode());
 		     	webMemberDetailService.add(baseDetail);
         	}
		  }
		} catch (Exception e) {
			
			data.setRelationStatus(false);
			data.setRelationMessage("建立关系错误");
		}
		
		return data;
	}
	

	/**
	 * 这里是扫码地址
	 * 这里主要功能是扫码进行关联关系确定   account token invitationCode
	 */
	public ResResult setRelation(TokenData temp,String subjectId){
		
		System.out.println("我下级的推荐码是:"+ subjectId);

		try {
			//判断token是不是存在
			if(StringHelper.isEmpty(temp.getToken())){
				return ResResult.error(1, "token不能为空");
			}
			//先判断token正确性
			boolean flag = TokenUtil.assertUserToken(temp);
			if(!flag){
				return ResResult.error(2, "token失效");
			}
			
			//从token中取account信息   
			temp.setAccount(TokenUtil.getUserList(temp.getToken()).getAccount().trim());
			
			WebMember member = webMemberService.getMemberByAccount(subjectId);
			System.out.println("扫码者的帐号是:"+member.getAccount());
			
			MemberView view = null;
			
			//扫码者用户信息
			WebMemberDetail subMemDetail = webMemberDetailService.getMemberDetailByAccount(temp.getAccount());
			if(subMemDetail !=null){
			       if(subMemDetail.getPid() == null || "".equals(subMemDetail.getPid())){
			       	view = new MemberView();
			       	subMemDetail.setPid(member.getAccount());
			       	webMemberDetailService.edit(subMemDetail);
			       	WebMember submember = webMemberService.getMemberByAccount(subMemDetail.getAccount());
			       	view.setId(submember.getId());
			       	view.setRealname(submember.getRealname());
			       	view.setPid(member.getAccount());
			       	//图片地址
			       	String memfileId = submember.getFileId();
			       	if(memfileId!=null && !"".equals(memfileId)){
			       		//ModelFiles file = modelFilesService.getFile(memfileId);
			       		ModelFiles modelFile = modelFilesService.get(submember.getFileId());
			       		if(modelFile!=null){
			       			view.setFileId(modelFile.getFilePath());
			       		}
			       	}
			       	return ResResult.build(200, "发展下级用户成功", view);
			       }else{
			       	return ResResult.error(3, "此用户已有上级");
			       }
			}else{
				return ResResult.error(5, "此用户不存在");
			}
		} catch (Exception e) {
			//返回错误代码
			e.printStackTrace();
			return ResResult.error(4, "扫码失败");
		}
		
	}
	

	/**
	 *查询用户信息
	 */
	public ResResult getMemInfo(TokenData data){
		
		
		WebMember member = null;
		try {
			//判断token是不是存在
			if(StringHelper.isEmpty(data.getToken())){
				return ResResult.error(1, "token不能为空");
			}
			//先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if(!flag){
				return ResResult.error(2, "token失效");
			}
			
			//从token中取account信息   
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			//取得用户信息
			System.out.println("现在要查询的帐号是:"+data.getAccount());
			member = webMemberService.getMemberByAccount(data.getAccount());
			
         	String memfileId = member.getFileId();
         	if(memfileId!=null && !"".equals(memfileId)){
         		ModelFiles file = modelFilesService.getFile(memfileId);
    		     if(file!=null){
    		    	 member.setFileId(file.getFilePath());
    		     }
         	}
			
			//过滤用户加密信息
			member.setVerificationCode(null);
			member.setPassword(null);
			member.setExpireTime(null);
			member.setVerificationExpireTime(null);
			
			return ResResult.build(200, "获取用户信息成功", member);
		} catch (Exception e) {
			//返回错误代码
			return ResResult.error(4, "getMemInfo调用失败");
		}
		
	}
	
	
	/**
	 *更新用户姓名
	 */
	public ResResult updateMemName(TokenData data,String realname){
		
		
		WebMember member = null;
		try {
			//判断token是不是存在
			if(StringHelper.isEmpty(data.getToken())){
				return ResResult.error(1, "token不能为空");
			}
			//先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if(!flag){
				return ResResult.error(2, "token失效");
			}
			
			//从token中取account信息   
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			//取得用户信息
			System.out.println("现在要查询的帐号是:"+data.getAccount());
			member = webMemberService.getMemberByAccount(data.getAccount());
			member.setRealname(realname);
			webMemberService.edit(member);
			
			//变更图片
         	String memfileId = member.getFileId();
         	if(memfileId!=null && !"".equals(memfileId)){
         		ModelFiles file = modelFilesService.getFile(memfileId);
    		     if(file!=null){
    		    	 member.setFileId(file.getFilePath());
    		     }
         	}
			
			//过滤用户加密信息
			member.setVerificationCode(null);
			member.setPassword(null);
			member.setExpireTime(null);
			member.setVerificationExpireTime(null);
			
			return ResResult.build(200, "更新用户信息成功", member);
		} catch (Exception e) {
			//返回错误代码
			return ResResult.error(4, "updateMemName调用失败");
		}
		
	}
	
	
	/**
	 *更新用户姓名
	 */
	public ResResult updateMemOSSImage(HttpServletRequest request,MultipartFile file,TokenData data){
		
		
		WebMember member = null;
		try {
			//判断token是不是存在
			if(StringHelper.isEmpty(data.getToken())){
				return ResResult.error(1, "token不能为空");
			}
			//先判断token正确性
			boolean flag = TokenUtil.assertUserToken(data);
			if(!flag){
				return ResResult.error(2, "token失效");
			}
			
			//从token中取account信息   
			data.setAccount(TokenUtil.getUserList(data.getToken()).getAccount().trim());
			//取得用户信息
			System.out.println("现在要查询的帐号是:"+data.getAccount());
			member = webMemberService.getMemberByAccount(data.getAccount());
			member.setFileId(null);
			webMemberService.edit(member);
			
			//变更图片
         	String memfileId = member.getFileId();
         	if(memfileId!=null && !"".equals(memfileId)){
         		ModelFiles memfile = modelFilesService.getFile(memfileId);
    		     if(file!=null){
    		    	 member.setFileId(memfile.getFilePath());
    		     }
         	}
			
			//过滤用户加密信息
			member.setVerificationCode(null);
			member.setPassword(null);
			member.setExpireTime(null);
			member.setVerificationExpireTime(null);
			
			return ResResult.build(200, "更新用户信息成功", member);
		} catch (Exception e) {
			//返回错误代码
			return ResResult.error(4, "updateMemName调用失败");
		}
		
	}
	
	
	
}
